﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Net;
using System.Web;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Utils;
using System.Linq;
using System.Threading;
namespace AutoAccepter
{
    public partial class Form1 : Form
    {

        int orderListrReviewTimes = 0;//用于记录检索工单列表次数
        int orderAcceptedCount = 0;//用于记录受理工单数量
        int reLoginTimes = 0;//用于记录重新登录次数
        List<string> accpetedOrderIDList = new List<string>();//用于记录已受理工单，避免重复受理
        System.Timers.Timer timer1 = new System.Timers.Timer(40000);
        public Form1()
        {
            Control.CheckForIllegalCrossThreadCalls = false;
            InitializeComponent();
            //执行登陆操作的worker
            loginBGWorker = new BackgroundWorker();
            loginBGWorker.DoWork += new DoWorkEventHandler(loginBGWorker_DoWork);
            loginBGWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(loginBGWorker_RunWorkerCompleted);
            //执行获取工单列表操作的worker
            getOrderListBGWorker = new BackgroundWorker();
            getOrderListBGWorker.DoWork += new DoWorkEventHandler(getOrderListBGWorker_DoWork);
            getOrderListBGWorker.WorkerSupportsCancellation = true;

            timer1.Elapsed += new System.Timers.ElapsedEventHandler(Timer1TODO);
            timer1.AutoReset = true;

            System.Net.ServicePointManager.DefaultConnectionLimit = 50;
            //CommonTool.cookie = new CookieContainer();
            System.GC.Collect();
        }

        private void loginbutton_Click(object sender, EventArgs e)
        {
            CommonTool.cookie = new CookieContainer();
            usernametb.Enabled = false;
            passwordtb.Enabled = false;
            loginbutton.Enabled = false;

            if (usernametb.Text != string.Empty && passwordtb.Text != string.Empty)
            {
                Flag flag = new Flag();
                loginBGWorker.RunWorkerAsync(flag);
            }
            else
            {
                MessageBox.Show("用户名或密码为空，请重新输入");
                usernametb.Enabled = true;
                passwordtb.Enabled = true;
                loginbutton.Enabled = true;
            }
        }

        private void startbutton_Click(object sender, EventArgs e)
        {
            startbutton.Enabled = false;
            stopbutton.Enabled = true;
            timer1.Start();
            getOrderListBGWorker.RunWorkerAsync();            
        }

        private void stopbutton_Click(object sender, EventArgs e)
        {
            LogHelper.WriteLog(typeof(Form1), "用户停止");
            timer1.Stop();
            getOrderListBGWorker.CancelAsync();
            startbutton.Enabled = true;
            stopbutton.Enabled = false;
        }

        private void logoutbutton_Click(object sender, EventArgs e)
        {
            LogHelper.WriteLog(typeof(Form1), "用户注销");
            CommonTool.cookie = new CookieContainer();
            usernametb.Enabled = true;
            passwordtb.Enabled = true;
            loginbutton.Enabled = true;
            startbutton.Enabled = false;
            stopbutton.Enabled = false;
            logoutbutton.Enabled = false;
            toolStripStatusLabel1.Text = "未登录";
            notifyIcon1.Text = "AutoAccepter";
            orderListrReviewTimes = 0;
            orderAcceptedCount = 0;
            label4.Text = "已检索0次工单";
            label3.Text = "已受理0张工单";
            label6.Text = "";
        }

        //登陆的方法
        private void login(string username, string password, Flag flag)
        {
            toolStripStatusLabel3.Text = "正在登陆...";            
            //尝试获取第一组cookie
            while (true)
            {
                try
                {
                    //创建打开登陆界面的请求
                    var get1stCookieRequest = CommonTool.CreateWebRequest("http://10.216.6.6/heeoms/roles/login.jsp");
                    get1stCookieRequest.Accept = "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/x-silverlight, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*";
                    get1stCookieRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727)";
                    get1stCookieRequest.Headers["Accept-Language"] = "zh-cn";
                    get1stCookieRequest.Headers["Accept-Encoding"] = "gzip, deflate";
                    get1stCookieRequest.KeepAlive = true;
                    get1stCookieRequest.Timeout = 10000;
                    //打开登录界面，并获取第一组Cookie
                    CommonTool.CreateGetHttpResponse(get1stCookieRequest);
                    break;
                }
                catch (WebException e)
                {
                    if (e.Message.Contains("操作超时"))
                    {
                        LogHelper.WriteLog(typeof(Form1), "网络超时(打开登录页)，重发请求，错误状态：" + e.Message + "/" + e.Status);
                        Console.WriteLine("网络超时(打开登录页)，重发请求，错误状态：" + e.Message + "/" + e.Status);
                    }
                    else
                    {
                        LogHelper.WriteLog(typeof(Form1), "网络错误(打开登录页)，60秒后重试，错误状态：" + e.Message + "/" + e.Status);
                        Console.WriteLine("网络错误(打开登录页)，60秒后重试，错误状态：" + e.Message + "/" + e.Status);
                        Thread.Sleep(60000);
                    }
                }
            }
            //尝试通过用户名密码获取第二组cookie           
            HttpWebResponse loginResp;
            //密码base64编码
            byte[] bytes = Encoding.Default.GetBytes(passwordtb.Text);
            string passwordBase64 = Convert.ToBase64String(bytes);
            //组成post内容
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic.Add("key1", usernametb.Text);
            dic.Add("key2", passwordBase64);
            while (true)
            {               
                try
                {
                    //创建使用用户名密码登陆的请求
                    var loginRequest = CommonTool.CreateWebRequest("http://10.216.6.6/heeoms/roles/login.do");
                    loginRequest.Accept = "application/xml, text/xml, */*";
                    loginRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727)";
                    loginRequest.Headers["Accept-Language"] = "zh-cn";
                    loginRequest.Headers["Accept-Encoding"] = "gzip, deflate";
                    loginRequest.KeepAlive = true;
                    loginRequest.Headers["x-requested-with"] = "XMLHttpRequest";
                    loginRequest.ContentType = "application/x-www-form-urlencoded";
                    loginRequest.Headers["Cache-Control"] = "no-cache";
                    loginRequest.Referer = "http://10.216.6.6/heeoms/roles/login.jsp";
                    loginRequest.Timeout = 10000;                    
                    loginResp = CommonTool.CreatePostHttpResponse(loginRequest, dic, Encoding.UTF8, true);
                    break;
                }
                catch (WebException e)
                {
                    if (e.Message.Contains("操作超时"))
                    {
                        LogHelper.WriteLog(typeof(Form1), "网络超时(获取第二组cookie)，重发请求，错误状态：" + e.Message + "/" + e.Status);
                        Console.WriteLine("网络超时(获取第二组cookie)，重发请求，错误状态：" + e.Message + "/" + e.Status);
                    }
                    else
                    {
                        LogHelper.WriteLog(typeof(Form1), "网络错误(获取第二组cookie)，60秒后重试，错误状态：" + e.Message + "/" + e.Status);
                        Console.WriteLine("网络错误(获取第二组cookie)，60秒后重试，错误状态：" + e.Message + "/" + e.Status);
                        Thread.Sleep(60000);
                    }
                }
            }

            //获取并判断登陆结果            
            var respStr = CommonTool.GetStringFromWebResponse(loginResp, Encoding.UTF8);
            //如果登陆成功，尝试获取第三组cookie，如果登陆失败，则返回登陆失败
            if (respStr.Contains("true"))
            {
                //创建获取第三组cookie的路径
                Regex reg = new Regex(@"(?<=<pass>).+(?=</pass>)");
                string get3rdCookiePath = "http://10.216.6.6:8090/bpp/portal/extentLogin.action?data=" + usernametb.Text + "%40semi%40" + System.Web.HttpUtility.UrlEncode(reg.Match(respStr).Groups[0].Value) + "&url=http://10.216.6.6:80/heeoms/common/jsp/index.jsp";
                //尝试获取第三组cookie
                //创建获取第三组cookie的请求                
                while (true)
                {
                    try
                    {
                        var get3rdCookieRequest = CommonTool.CreateWebRequest(get3rdCookiePath);
                        get3rdCookieRequest.Accept = "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/x-silverlight, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*";
                        get3rdCookieRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727)";
                        get3rdCookieRequest.Headers["Accept-Language"] = "zh-cn";
                        get3rdCookieRequest.Headers["Accept-Encoding"] = "gzip, deflate";
                        get3rdCookieRequest.KeepAlive = true;
                        get3rdCookieRequest.AllowAutoRedirect = false;
                        get3rdCookieRequest.Timeout = 10000;
                        CommonTool.CreateGetHttpResponse(get3rdCookieRequest);
                        break;
                    }
                    catch (WebException e)
                    {
                        if (e.Message.Contains("操作超时"))
                        {
                            LogHelper.WriteLog(typeof(Form1), "网络超时(获取第三组cookie)，重发请求，错误状态：" + e.Message + "/" + e.Status);
                            Console.WriteLine("网络超时(获取第三组cookie)，重发请求，错误状态：" + e.Message + "/" + e.Status);
                        }
                        else
                        {
                            LogHelper.WriteLog(typeof(Form1), "网络错误(获取第三组cookie)，60秒后重试，错误状态：" + e.Message + "/" + e.Status);
                            Console.WriteLine("网络错误(获取第三组cookie)，60秒后重试，错误状态：" + e.Message + "/" + e.Status);
                            Thread.Sleep(60000);
                        }
                    }
                }                               
                Console.WriteLine("登陆成功");               
                flag.isLogin = true;
            }
            else
            {                
                Console.WriteLine("登陆失败");
                flag.isLogin = false;
            }
        }

        //判断登陆状态、获取未工单列表、受理工单的方法
        private void getOrderList()
        {
            try
            {
                //获取首页工单列表
                toolStripStatusLabel3.Text = "正在获取工单列表...";
                LogHelper.WriteLog(typeof(Form1), "正在进行第" + (orderListrReviewTimes + 1) + "次工单检索");
                HttpWebResponse get1stPageOrderListResp = null;
                while (true)
                {
                    try
                    {
                        var get1stPageOrderListRequest = CommonTool.CreateWebRequest("http://10.216.6.6/heeoms/UltraProcess/BaseQuery/QueryWaitDealNew.jsp?action=DEAL&flowversion=1,2");
                        get1stPageOrderListRequest.Accept = "text/html, application/xhtml+xml, image/jxr, */*";
                        get1stPageOrderListRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727)";
                        get1stPageOrderListRequest.Headers["Accept-Language"] = "zh-Hans-CN,zh-Hans;q=0.5";
                        get1stPageOrderListRequest.Headers["Accept-Encoding"] = "gzip, deflate";
                        get1stPageOrderListRequest.KeepAlive = true;
                        get1stPageOrderListRequest.AllowAutoRedirect = true;
                        get1stPageOrderListRequest.Timeout = 60000;
                        get1stPageOrderListResp = CommonTool.CreateGetHttpResponse(get1stPageOrderListRequest);
                        break;
                    }
                    catch (WebException e)
                    {
                        if (e.Message.Contains("操作超时"))
                        {
                            LogHelper.WriteLog(typeof(Form1), "网络超时(获取首页工单)，重发请求，错误状态：" + e.Message + "/" + e.Status);
                            Console.WriteLine("网络超时(获取首页工单)，重发请求，错误状态：" + e.Message + "/" + e.Status);
                        }
                        else
                        {
                            LogHelper.WriteLog(typeof(Form1), "网络错误(获取首页工单)，当前进程终止，错误状态：" + e.Message + "/" + e.Status);
                            Console.WriteLine("网络错误(获取首页工单)，当前进程终止，错误状态：" + e.Message + "/" + e.Status);
                            throw e;
                        }
                    }
                }
                //判断登陆状态
                if ((int)get1stPageOrderListResp.StatusCode == 200)
                {
                    var get1stPageOrderListRespStr = CommonTool.GetStringFromWebResponse(get1stPageOrderListResp, Encoding.UTF8);
                    //获取工单页数
                    Regex reg = new Regex(@"(?<=/)\d+(?=&nbsp)");
                    var listPageCount = Int32.Parse(reg.Match(get1stPageOrderListRespStr).Groups[0].Value);
                    LogHelper.WriteLog(typeof(Form1), "当前共有" + listPageCount + "页工单");
                    Console.WriteLine("当前共有" + listPageCount + "页工单");
                    //生成未受理工单列表
                    //LogHelper.WriteLog(typeof(Form1), "正在检索第1页工单");
                    List<Order> unAccepedOrderList = Order.Parse(get1stPageOrderListRespStr);
                    if (listPageCount > 1)
                    {
                        for (int i = 2; i <= listPageCount; i++)
                        {
                            //生成post的dic
                            Dictionary<string, string> dic = new Dictionary<string, string>();
                            dic.Add("showOrNot", "0");
                            dic.Add("pageNumber", i.ToString());
                            dic.Add("pageCount", listPageCount.ToString());
                            dic.Add("pageSize", "20");
                            dic.Add("isfirst", "2");
                            dic.Add("txtSortfiled", "BaseDealOutTime");
                            dic.Add("sortType", "0");
                            dic.Add("action", "DEAL");
                            dic.Add("BaseSN", "");
                            dic.Add("BaseSummary", "");
                            dic.Add("BaseCreatorFullName", "");
                            dic.Add("BaseCreateDate1", "");
                            dic.Add("BaseCreateDate2", "");
                            dic.Add("BaseStatus", "");
                            dic.Add("BasePriority", "");
                            dic.Add("IsNeedCloseByPerson", "");
                            dic.Add("BaseItems", "");
                            //获取第i页工单列表
                            HttpWebResponse getCurrentPageOrderListResp = null;
                            while (true)
                            {
                                try
                                {
                                    var getCurrentPageOrderListRequest = CommonTool.CreateWebRequest("http://10.216.6.6/heeoms/UltraProcess/BaseQuery/QueryWaitDealNew.jsp?action=DEAL&flowversion=1,2");
                                    getCurrentPageOrderListRequest.Accept = "image/gif, image/jpeg, image/pjpeg, application/x-ms-application, application/xaml+xml, application/x-ms-xbap, */*";
                                    getCurrentPageOrderListRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727)";
                                    getCurrentPageOrderListRequest.Headers["Accept-Language"] = "zh-Hans-CN,zh-Hans;q=0.5";
                                    getCurrentPageOrderListRequest.Headers["Accept-Encoding"] = "gzip, deflate";
                                    getCurrentPageOrderListRequest.KeepAlive = true;
                                    getCurrentPageOrderListRequest.ContentType = "application/x-www-form-urlencoded";
                                    getCurrentPageOrderListRequest.Headers["Cache-Control"] = "no-cache";
                                    getCurrentPageOrderListRequest.Referer = "http://10.216.6.6/heeoms/UltraProcess/BaseQuery/QueryWaitDealNew.jsp?action=DEAL&flowversion=1,2";
                                    getCurrentPageOrderListRequest.Timeout = 60000;
                                    getCurrentPageOrderListResp = CommonTool.CreatePostHttpResponse(getCurrentPageOrderListRequest, dic, Encoding.UTF8, true);
                                    break;
                                }
                                catch (WebException e)
                                {
                                    if (e.Message.Contains("操作超时"))
                                    {
                                        LogHelper.WriteLog(typeof(Form1), "网络超时(获取第" + i + "页工单列表)，重发请求，错误状态：" + e.Message + "/" + e.Status);
                                        Console.WriteLine("网络超时(获取第" + i + "页工单列表)，重发请求，错误状态：" + e.Message + "/" + e.Status);
                                    }
                                    else
                                    {
                                        LogHelper.WriteLog(typeof(Form1), "网络错误(获取第" + i + "页工单列表)，当前进程终止，错误状态：" + e.Message + "/" + e.Status);
                                        Console.WriteLine("网络错误(获取第" + i + "页工单列表)，当前进程终止，错误状态：" + e.Message + "/" + e.Status);
                                        throw e;
                                    }
                                }
                            }
                            //将当前页未受理工单放入未受理工单列表
                            if ((int)getCurrentPageOrderListResp.StatusCode == 200)
                            {
                                var getCurrentPageOrderListRespStr = CommonTool.GetStringFromWebResponse(getCurrentPageOrderListResp, Encoding.UTF8);
                                //LogHelper.WriteLog(typeof(Form1), "正在检索第" + i + "页工单");
                                List<Order> currentPageUnAccepedOrderList = Order.Parse(getCurrentPageOrderListRespStr);
                                unAccepedOrderList = unAccepedOrderList.Union(currentPageUnAccepedOrderList).ToList<Order>();
                            }
                            else
                            {
                                LogHelper.WriteLog(typeof(Form1), "发现登录超时(获取第" + i + "页工单列表)，重新登录");
                                CommonTool.cookie = new CookieContainer();
                                Flag flag = new Flag();
                                flag.isReLogin = true;
                                loginBGWorker.RunWorkerAsync(flag);
                            }
                        }
                    }
                    //排除前期已受理工单
                    for (int i = unAccepedOrderList.Count - 1; i >= 0; i--)
                    {
                        if (accpetedOrderIDList.Contains(unAccepedOrderList[i].id))
                        {
                            unAccepedOrderList.Remove(unAccepedOrderList[i]);
                        }
                    }

                    //打印已检索工单次数和当前未受理工单数

                    Console.WriteLine("当前共有" + unAccepedOrderList.Count + "张未受理故障处理工单or事件告警");
                    LogHelper.WriteLog(typeof(Form1), "当前共有" + unAccepedOrderList.Count + "张未受理故障处理工单or事件告警");
                    //受理unAccepedOrderList中的工单
                    if (unAccepedOrderList.Count > 0)
                    {
                        int i = 0;
                        foreach (Order order in unAccepedOrderList)
                        {
                            i++;
                            //从工单url中提取baseID和taskID
                            Regex baseIDReg = new Regex(@"(?<=baseID=)\w+(?=&)");
                            Regex taskIDReg = new Regex(@"(?<=taskID=)\w+(?=&)");
                            string baseID = baseIDReg.Match(order.url).Groups[0].Value;
                            string taskID = taskIDReg.Match(order.url).Groups[0].Value;

                            Console.WriteLine("第" + i + "张故障处理工单or事件告警的baseID为：" + baseID);
                            Console.WriteLine("第" + i + "张故障处理工单or事件告警的taskID为：" + taskID);

                            //判断当前待受理工单是故障处理工单还是事件告警
                            Dictionary<string, string> dic = new Dictionary<string, string>();
                            string requestRefererPath = "";                            

                            if (order.type.Contains("事件告警"))
                            {
                                dic.Add("bpp_Sys_BaseID", baseID);
                                dic.Add("bpp_Sys_BaseSchema", "EL_EVENT_ALARM");
                                dic.Add("bpp_Sys_DefCode", "EL_EVENT_ALARM-20150324043137");
                                dic.Add("bpp_Sys_FlagActive", "1");
                                dic.Add("bpp_Sys_TaskID", taskID);
                                dic.Add("bpp_Sys_ActionID", "ACCEPT");
                                dic.Add("bpp_Sys_ActionType", "ACCEPT");
                                dic.Add("bpp_Sys_ActionText", "受理");
                                dic.Add("bpp_Sys_CloseAfterCommit", "0");
                                requestRefererPath = "http://10.216.6.6:8090/bpp/ultrabpp/view.action?baseSchema=EL_EVENT_ALARM&baseID=" + baseID + "&taskID=" + taskID + "&mode=MODIFY";
                            }
                            else 
                            {
                                dic.Add("bpp_Sys_BaseID", baseID);
                                dic.Add("bpp_Sys_BaseSchema", "EL_TTM_TTH");
                                dic.Add("bpp_Sys_DefCode", "EL_TTM_TTH-20150324043137");
                                dic.Add("bpp_Sys_FlagActive", "1");
                                dic.Add("bpp_Sys_TaskID", taskID);
                                dic.Add("bpp_Sys_ActionID", "ACCEPT");
                                dic.Add("bpp_Sys_ActionType", "ACCEPT");
                                dic.Add("bpp_Sys_ActionText", "受理");
                                dic.Add("bpp_Sys_CloseAfterCommit", "0");
                                requestRefererPath = "http://10.216.6.6:8090/bpp/ultrabpp/view.action?baseSchema=EL_TTM_TTH&baseID=" + baseID + "&taskID=" + taskID + "&mode=MODIFY";
                            }
                                
                            HttpWebResponse acceptResp = null;

                            while (true)
                            {
                                try
                                {
                                    //创建受理post请求
                                    var request = CommonTool.CreateWebRequest("http://10.216.6.6:8090/bpp/ultrabpp/form/formAction/save.action");
                                    request.Accept = "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-silverlight, application/xaml+xml, application/x-ms-xbap, application/x-ms-application, */*";
                                    request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727)";
                                    request.Headers["Accept-Language"] = "zh-cn";
                                    request.Headers["Accept-Encoding"] = "gzip, deflate";
                                    request.KeepAlive = true;
                                    request.Headers["x-requested-with"] = "XMLHttpRequest";
                                    request.ContentType = "application/x-www-form-urlencoded";
                                    request.Headers["Cache-Control"] = "no-cache";
                                    request.Referer = requestRefererPath;
                                    request.Timeout = 10000;
                                    request.AllowAutoRedirect = false;

                                    acceptResp = CommonTool.CreatePostHttpResponse(request, dic, Encoding.UTF8, true);
                                    break;
                                }
                                catch (WebException e)
                                {
                                    if (e.Message.Contains("操作超时"))
                                    {
                                        LogHelper.WriteLog(typeof(Form1), "网络超时(受理工单)，重发请求，错误状态：" + e.Message + "/" + e.Status);
                                        Console.WriteLine("网络超时(受理工单)，重发请求，错误状态：" + e.Message + "/" + e.Status);
                                    }
                                    else
                                    {
                                        LogHelper.WriteLog(typeof(Form1), "网络错误(受理工单)，当前进程终止，错误状态：" + e.Message + "/" + e.Status);
                                        Console.WriteLine("网络错误(受理工单)，当前进程终止，错误状态：" + e.Message + "/" + e.Status);
                                        throw e;
                                    }
                                }
                            }


                            //Console.WriteLine("受理工单请求的回应状态码为：" + (int)acceptResp.StatusCode);
                            //判断登陆状态
                            if ((int)acceptResp.StatusCode == 200)
                            {
                                orderAcceptedCount = orderAcceptedCount + 1;
                                accpetedOrderIDList.Add(order.id);
                                label3.Text = "已受理" + orderAcceptedCount + "张工单";
                                Console.WriteLine("已受理第" + i + "张故障处理工单or事件告警，工单号为" + order.id);
                                LogHelper.WriteLog(typeof(Form1), "已受理工单编号为" + order.id + "的工单");
                            }
                            else
                            {
                                LogHelper.WriteLog(typeof(Form1), "发现登录超时(受理工单)，重新登录");
                                CommonTool.cookie = new CookieContainer();
                                Flag flag = new Flag();
                                flag.isReLogin = true;
                                loginBGWorker.RunWorkerAsync(flag);
                            }

                        }
                    }
                    orderListrReviewTimes = orderListrReviewTimes + 1;
                    label4.Text = "已检索" + orderListrReviewTimes + "次工单";
                    LogHelper.WriteLog(typeof(Form1), "已完成第" + orderListrReviewTimes + "次工单检索" + System.Environment.NewLine);
                    toolStripStatusLabel3.Text = "当前无操作";
                }
                else
                {
                    LogHelper.WriteLog(typeof(Form1), "发现登录超时(获取首页工单列表)，重新登录");
                    CommonTool.cookie = new CookieContainer();
                    Flag flag = new Flag();
                    flag.isReLogin = true;
                    loginBGWorker.RunWorkerAsync(flag);
                }
            }
            catch (Exception e)
            {
                if (e.Message.Contains("内部服务器错误"))
                {
                    LogHelper.WriteLog(typeof(Form1), "发生内部服务器错误异常，尝试重新登录");
                    CommonTool.cookie = new CookieContainer();
                    Flag flag = new Flag();
                    flag.isReLogin = true;
                    loginBGWorker.RunWorkerAsync(flag);
                }
                else
                {
                    LogHelper.WriteLog(typeof(Form1), "发生异常，当前进程终止，异常状态：" + e.Message);
                }                
            }                                 
        }
        //执行登陆操作的worker的两个方法
        private void loginBGWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            Flag flag = e.Argument as Flag;
            login(usernametb.Text, passwordtb.Text, flag);
            e.Result = flag;
        }
        private void loginBGWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            Flag flag = e.Result as Flag;
            if (flag.isReLogin == false)
            {
                if (flag.isLogin)
                {
                    LogHelper.SetPath(usernametb.Text);
                    LogHelper.WriteLog(typeof(Form1), "登录成功 " + usernametb.Text);
                    MessageBox.Show("登陆成功，点击开始按钮开始自动受理工单");
                    toolStripStatusLabel1.Text = "已登录：" + usernametb.Text;
                    toolStripStatusLabel3.Text = "当前无操作";
                    notifyIcon1.Text = "AutoAccepter:" + usernametb.Text;                   
                    startbutton.Enabled = true;
                    logoutbutton.Enabled = true;
                }
                else
                {
                    LogHelper.WriteLog(typeof(Form1), "登录失败，用户名密码错误");
                    MessageBox.Show("用户名密码错误，请重新登录");
                    toolStripStatusLabel3.Text = "当前无操作";
                    usernametb.Enabled = true;
                    passwordtb.Enabled = true;
                    loginbutton.Enabled = true;
                }
            }
            else
            {
                if (flag.isLogin)
                {
                    reLoginTimes = reLoginTimes + 1;
                    toolStripStatusLabel3.Text = "重新登陆成功";
                    LogHelper.WriteLog(typeof(Form1), "重新登陆成功");
                    label6.Text = "已重新登录" + reLoginTimes + "次";
                    Thread.Sleep(3000);
                    toolStripStatusLabel3.Text = "当前无操作";
                }
                else
                {
                    timer1.Stop();
                    CommonTool.cookie = new CookieContainer();
                    Console.WriteLine("当前登陆已超时");
                    MessageBox.Show("登陆已超时，重新登陆失败");
                    LogHelper.WriteLog(typeof(Form1), "登陆已超时，重新登陆失败，软件初始化");
                    usernametb.Enabled = true;
                    passwordtb.Enabled = true;
                    loginbutton.Enabled = true;
                    startbutton.Enabled = false;
                    stopbutton.Enabled = false;
                    logoutbutton.Enabled = false;
                    toolStripStatusLabel1.Text = "未登录";
                    orderListrReviewTimes = 0;
                    orderAcceptedCount = 0;
                    label4.Text = "已检索0次工单";
                    label3.Text = "已受理0张工单";
                }
            }
            
        }
        //执行获取工单列表操作的worker的方法
        private void getOrderListBGWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            getOrderList();
        }        

        //定时器代码
        public void Timer1TODO(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (!getOrderListBGWorker.IsBusy)
            {
                getOrderListBGWorker.RunWorkerAsync();
            }          
        }

        //托盘图标双击事件
        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (WindowState == FormWindowState.Minimized)
            {
                //还原窗体显示    
                WindowState = FormWindowState.Normal;
                //激活窗体并给予它焦点
                this.Activate();
                //任务栏区显示图标
                this.ShowInTaskbar = true;
                //托盘区图标隐藏
                //notifyIcon1.Visible = false;
            }
        }
        //最小化到托盘
        private void F_Main_SizeChanged(object sender, EventArgs e)
        {
            //判断是否选择的是最小化按钮
            if (WindowState == FormWindowState.Minimized)
            {
                //隐藏任务栏区图标
                this.ShowInTaskbar = false;
                //图标显示在托盘区
                notifyIcon1.Visible = true;
            }
        }
        //退出提示
        private void F_Main_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (MessageBox.Show("是否确认退出程序？", "退出", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                this.Dispose();
                this.Close();
            }
            else
            {
                e.Cancel = true;
            }
        }

        private void label5_Click(object sender, EventArgs e)
        {

        }
    }
    //中介类
    internal class Flag
    {
        public bool isLogin = false;
        public bool isReLogin = false;
    }
}